﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DGIS.SysSetting.Core.Service.Win;

namespace Test.Network
{
    public partial class NetworkFrm : Form
    {
        private NetworkService _networkService;
        public NetworkFrm()
        {
            InitializeComponent();
        }

        private void NetworkFrm_Load(object sender, EventArgs e)
        {
            Init();
        }

        private void NetworkCbox_SelectedIndexChanged(object sender, EventArgs e)
        {
            string name = this.networkCbox.SelectedItem.ToString();
            DGIS.SysSetting.Core.Model.Network item = GetNetworkSetting(name);

            BindData(item);
        }

        private void saveBtn_Click(object sender, EventArgs e)
        {
            string ip = this.ipTextbox.Text.Trim();
            string mask = this.maskTextbox.Text.Trim();
            string gateway = this.gatewayTextbox.Text.Trim();
            string dns1 = this.dns1Textbox.Text.Trim();
            string dns2 = this.dns2Textbox.Text.Trim();

            string name = this.networkCbox.SelectedItem.ToString();
            bool enbaleDHCP = this.enableDHCPCheckbox.Checked;

            DGIS.SysSetting.Core.Model.Network item = new DGIS.SysSetting.Core.Model.Network()
            {
                Name = name,
                Ip = ip,
                Mask = mask,
                Gateway = gateway,
                EnableDHCP = enbaleDHCP,
                Dns = new List<string>()
                {
                    dns1,dns2
                }
            };

            bool result = _networkService.Set(item);
            MessageBox.Show(result ? "操作成功" : "操作失败");
        }

        private void Init()
        {
            _networkService = new NetworkService();

            //01 获取网卡列表
            List<DGIS.SysSetting.Core.Model.Network> items = _networkService.GetList();

            //02 绑定网卡列表控件
            this.networkCbox.Items.Clear();
            this.networkCbox.SelectedIndexChanged += NetworkCbox_SelectedIndexChanged;
            foreach (DGIS.SysSetting.Core.Model.Network item in items)
            {
                this.networkCbox.Items.Add(item.Name);
            }
        }


        private void BindData(DGIS.SysSetting.Core.Model.Network item)
        {
            this.ipTextbox.Text = item.Ip;
            this.maskTextbox.Text = item.Mask;
            this.gatewayTextbox.Text = item.Gateway;
            this.dns1Textbox.Text = item.Dns[0];
            if (item.Dns.Count > 1)
                this.dns2Textbox.Text = item.Dns[1];
        }

        private DGIS.SysSetting.Core.Model.Network GetNetworkSetting(string name)
        {
            return _networkService.Get(name);
        }
    }
}
